package com.zgjkhis.modules.util;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zgjkhis.modules.charges.domain.Logistics;
import com.zgjkhis.modules.charges.domain.PrescriptionOrder;
import com.zgjkhis.modules.charges.service.PrescriptionService;
import com.zgjkhis.modules.system.domain.ApiChannel;
import com.zgjkhis.modules.system.service.ApiChannelService;
import com.zgjkhis.utils.DateUtils;
import com.zgjkhis.utils.RandomUtils;
import com.zgjkhis.utils.RedisUtil;
import com.zgjkhis.utils.SpringContextHolder;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 物流回调接口
 */
@Slf4j
public class LogisticsUtil {

    private static final PrescriptionService prescriptionService;
    private static final ApiChannelService apiChannelService;


    static{
        prescriptionService = SpringContextHolder.getBean(PrescriptionService.class);
        apiChannelService = SpringContextHolder.getBean(ApiChannelService.class);
    }


    /**
     * @param orderNos //处方号
     * @param orderStatus //订单状态 1 待发货/待自取 ； 2 待收货/待自取  ；3已收货
     * @param shunFenJson
     */
    public static void sendLogistic(List<String> orderNos, Logistics logistics, String orderStatus, JSONObject shunFenJson,String type){

        JSONArray array=new JSONArray();
        for (int i=0;i<orderNos.size();i++) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("orderNo", orderNos.get(i));
            jsonObject.put("expressNum", logistics.getMailNo());
            jsonObject.put("bspOrderNo", logistics.getBspOrderNo());
            jsonObject.put("orderStatus", orderStatus);
            jsonObject.put("type", type);
            if(!CharUtil.isEmpty(shunFenJson)) {
                jsonObject.put("logistics", shunFenJson.toJSONString());
            }
            array.add(jsonObject);
        }
        PrescriptionOrder order = prescriptionService.getOne(Wrappers.<PrescriptionOrder>query().lambda().eq(PrescriptionOrder::getOrderNo, logistics.getOrderNo()));
        Object o = RedisUtil.get("phis:admin:callback:" + order.getSourceId());
        ApiChannel apiChannel=CharUtil.isEmpty(o)?null:(ApiChannel) o;
        if(CharUtil.isEmpty(apiChannel)) {
            apiChannel = apiChannelService.getOne(Wrappers.<ApiChannel>query().lambda().eq(ApiChannel::getStatus, 0).eq(ApiChannel::getAppId, order.getSourceId()));
            RedisUtil.set("phis:admin:callback:" + order.getSourceId(), apiChannel);
        }
        String data = JSON.toJSONString(array);
        data= RSAUtil.encode(apiChannel.getCallBackPublicKey(),data);
        JSONObject reqBodyObj = new JSONObject();
        reqBodyObj.put("appId", apiChannel.getCallBackAppId());
        reqBodyObj.put("data", data);
        String result = ConnectionUrlUtil.sendJsonPost(apiChannel.getCallBackUrl(), reqBodyObj.toJSONString());
        log.info("接口回调报文：{}",result);
        if(CharUtil.isEmpty(result) || !JSONObject.parseObject(result).getString("code").equals("200")){
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("url",apiChannel.getCallBackUrl());
            jsonObject.put("data",reqBodyObj.toJSONString());
            jsonObject.put("serialNumber", DateUtils.dateTimeNow()+ RandomUtils.getRandomNumbers(6));
            RedisUtil.convertAndSend("logictis",jsonObject);
        }
        log.info("物流回调接口："+result);
    }




    /**
     * 查询物流路由
     */
    public static String listOrderRoute(String mailNo, String appId, String appIdSecret, String baseUrl){
        String result=null;
        try {
            Map param= new HashMap<>();
            param.put("mailNo",mailNo);
            String version="1.0.0";
            String timestamp=System.currentTimeMillis()+"";
            String sign= SecureUtil.md5(appId+version+timestamp+appIdSecret);
            String urlParam="appid="+appId+"&version="+version+"&timestamp="+timestamp+"&sign="+sign;
             result= HttpUtil.get(baseUrl+"listOrderRoute?"+urlParam,param);
            log.info("{}查询物流信息返回报文：{}",mailNo,result);
        }catch (Exception e){
            log.error("{}查询物流信息错误:{}",mailNo,e);
        }
        return result;
    }

}
